import Vue from 'vue'
import Vuex from 'vuex'
import userModule from './user-module'

Vue.use(Vuex)

// 读取 localStorage 中保存的购物车数据
const cart = JSON.parse(localStorage.getItem('cart')) || []

const cartStorage = store => {
  store.subscribe((mutations, state) => {
    switch (mutations.type) {
      case 'addToCart': // 加入购物车
      case 'removeFromCart': // 从订单中删除
      case 'modifyAmount': // 修改购物车中商品数量
      case 'changeProdChecked': // 修改商品选中状态
      case 'checkAll': // 选中所有
        localStorage.setItem('cart', JSON.stringify(state.cart))
        break
    }
  })
}

// 定义用户状态变化时保存 localStorage 的插件
const userStorage = store => {
  store.subscribe((mutations, state) => {
    switch (mutations.type) {
      case 'login':
        localStorage.setItem('user', JSON.stringify(state.user))
        break
      case 'logout':
        localStorage.removeItem('user')
        break
    }
  })
}

// 创建 store: store 用户存储数据以及数据更新的动作
const store = new Vuex.Store({
  strict: true, // 严格模式
  plugins: [cartStorage, userStorage],
  modules: {
    user: userModule
  },
  state: {
    cart // 购物车数组
  },
  getters: {
    allChecked (state) { // 计算是否购物车中所有商品都被选中
      return state.cart.every(prod => prod.checked)
    },
    totalMoney (state) {
      return state.cart.reduce((result, prod) => {
        if (prod.checked) {
          result += prod.payMoney
        }
        return result
      }, 0)
    }
  },
  mutations: {
    addToCart (state, payload) {
      const cart = [...state.cart]
      const hasExist = cart.some(prod => prod.payId === payload.payId)
      if (hasExist) { // 已存在当前选购的商品
        console.log('有了')
      } else { // 不存在，则将当前选购商品直接添加到数组中
        // 第一次加入购物车，添加默认未选中的状态
        payload.checked = false
        // 加入购物车数组中
        state.cart = [
          ...cart,
          payload
        ]
      }
    },
    removeFromCart (state, payload) {
      state.cart = state.cart.filter(prod => prod.payId !== payload)
    },
    changeProdChecked (state, id) {
      const cart = [...state.cart]
      state.cart = cart.map(prod => {
        if (prod.payId === id) {
          prod.checked = !prod.checked
        }
        return prod
      })
    },
    submitHandler (state) {
      sessionStorage.removeItem('payData')
      const cart = [...state.cart]
      state.cart = cart.map(prod => {
        if (prod.checked) {
          const payDataVal = prod
          const payData = JSON.parse(sessionStorage.getItem('payData'))
          if (payData) {
            // const a = payData.find(payData => payData.payId === prod.payId)
            const hasExist = payData.some(item => item.payId === payDataVal.payId)
            if (hasExist) {
              console.log('已经有了')
            } else {
              this.payDataVal = [
                ...payData,
                payDataVal
              ]
              sessionStorage.setItem('payData', JSON.stringify(this.payDataVal))
            }
          } else {
            sessionStorage.setItem('payData', JSON.stringify([payDataVal]))
          }
        }
        return prod
      })
    },
    checkAll (state, checkedStatus) {
      const cart = [...state.cart]
      state.cart = cart.map(prod => {
        prod.checked = !checkedStatus
        return prod
      })
    }
  },
  actions: {}
})

export default store
